import store from './store'
import axios from 'axios'
import qs from 'qs'
import controls from './controls/controls'
import config from '../config'
import { useRouter } from 'vue-router'
const router = useRouter()

export default {
    store,
    wait(n) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve()
            }, n * 1000);
        })
    },
    async requestData(path = '', data = {}, method = 'post', loading = true) {
        method = method.toLocaleLowerCase()
        const handle = async (url, data) => {
            console.log(`请求 - 开始`, path, method, data)
            let re
            if (method == 'get') {
                re = await axios.get(config.apiPrefix + url + `?${qs.stringify(data)}`)
            } else {
                re = await axios.post(config.apiPrefix + url, data)
            }
            console.log(`请求 - 结束`, re.data)
            return re.data
        }
        if (loading) {
            controls.loading.show({ mask: true, title: '请稍候' })
        }
        try {
            let re = await handle(path, data)
            if (loading) {
                controls.loading.hide()
            }
            return re
        } catch (error) {
            if (loading) {
                controls.loading.hide()
            }
            return {
                status: 0,
                content: `${error}`
            }
        }
    },
    selectFiles(maxFiles = -1) {
        return new Promise((resolve, reject) => {
            const input = document.createElement('input');
            input.type = 'file';
            input.multiple = true;
            input.onchange = async (event) => {
                const files = Array.from(event.target.files);
                if (maxFiles != -1 && files.length > maxFiles) {
                    return reject(new Error(`你最多只能选择${maxFiles}个文件`));
                }
                const fileInfoPromises = files.map(async file => {
                    const fileData = await getFileData(file);
                    return {
                        name: file.name,
                        path: file.webkitRelativePath || file.name,
                        size: file.size,
                        createdAt: file.lastModifiedDate,  // 浏览器无法获取创建时间，只能获取最后修改时间
                        updatedAt: file.lastModifiedDate,
                        extension: getFileExtension(file.name),
                        baseName: getBaseName(file.name),
                        data: fileData
                    };
                });
                const fileInfoArray = await Promise.all(fileInfoPromises);
                resolve(fileInfoArray);
            };
            input.click();
        });
    },
    Object: {
        assign(o1, o2) {
            return Object.assign(JSON.parse(JSON.stringify(o1)), o2)
        }
    },
    controls,
    routerf() {
        return useRouter()
    },
    setTimeout: setTimeout,
    localStorage: {
        setItem(key, value) {
            let type = ''
            if (value instanceof Date) {
                type = 'date'
                value = value.getTime()
            } else if (value === undefined) {
                type = 'undefined'
                value = 'undefined'
            } else if (value === null) {
                type = 'null'
                value = 'null'
            } else {
                type = 'other'
            }
            value = JSON.stringify(value)
            localStorage.setItem(key, JSON.stringify({
                type,
                value
            }))
        },
        getItem(key) {
            let value = localStorage.getItem(key)
            if (value === null) return null
            value = JSON.parse(value)
            if (value.type === 'undefined') return undefined
            if (value.type === 'null') return null
            if (value.type === 'date') return new Date(value.value)
            return JSON.parse(value.value)
        },
        removeItem(key) {
            localStorage.removeItem(key)
        }
    },
    router: {
        push: (path) => {
            store.setItem('router_push', path)
        }
    },
    debounce(func, wait = 300) {
        let timeout;
        return function (...args) {
            const later = () => {
                clearTimeout(timeout);
                func.apply(this, args);
            };

            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },
    focusElementById(elementId) {
        const element = document.getElementById(elementId);
        if (element) {
            element.focus();
        } else {
            console.error(`Element with ID ${elementId} not found.`);
        }
    }
}


function getFileExtension(fileName) {
    return fileName.split('.').pop();
}

function getBaseName(fileName) {
    return fileName.substring(0, fileName.lastIndexOf('.')) || fileName;
}

function getFileData(file) {
    return new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = () => {
            const blobURL = URL.createObjectURL(new Blob([reader.result]));
            const formData = new FormData();
            formData.append('file', file);
            resolve({
                blobURL,
                file,
                formData
            });
        };
        reader.readAsArrayBuffer(file);
    });
}